package com.auxgroup.smarthome.event;

import com.alibaba.fastjson.JSONObject;
import com.auxgroup.smarthome.app.entity.SmartElectricityRedis;
import com.auxgroup.smarthome.app.service.SmartElectricityExecuteService;
import com.auxgroup.smarthome.constant.cache.CachedConsant;
import com.auxgroup.smarthome.enterprise.datapoint.consant.DatapointConsant;
import com.auxgroup.smarthome.enterprise.service.DeviceManageService;
import com.auxgroup.smarthome.redis.config.ObjectRedis;
import com.auxgroup.smarthome.service.AppControlFuncService;
import com.auxgroup.smarthome.snoti.events.IPushEvent;
import com.auxgroup.smarthome.utils.NewDateUtils;
import com.auxgroup.smarthome.utils.common.LOG;
import com.auxgroup.smarthome.vo.AppPeakValleyRedisEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.format.DateTimeFormatter;

/**
 * @Author: laiqiuhua.
 * @Date: 2017/9/19 11:01.
 **/
@Component
public class SmartElectricityEvent implements IPushEvent {

  @Autowired private DeviceManageService deviceManageService;

  @Autowired private SmartElectricityExecuteService smartElectricityExecuteService;

  @Autowired private ObjectRedis objectRedis;

  @Autowired private AppControlFuncService appControlFuncService;

  // 默认下发功率
  @Value("${smartElectricity.defaultPower}")
  private int defaultPower = 100;

  @Override
  public void callback(String message) {
    JSONObject msg = JSONObject.parseObject(message);
    String productKey = msg.getString("product_key");
    String mac = msg.getString("mac").toUpperCase();
    String did = msg.getString("did");
    JSONObject data = msg.getJSONObject("data");
    Integer airConFunc = data != null ? data.getInteger("air_con_func") : null;
    Integer fromReport = data != null ? data.getInteger("from_report") : null;
    Integer onOff = data != null ? data.getInteger("on_off") : null;
    // 0：自定义睡眠关, 1:自定义睡眠开(注：商用空调机无自定义睡眠，此字段为空)
    Integer sleepDiy = data.getInteger("sleep_diy");

    StringBuffer logStr = new StringBuffer();
    logStr.append("[status_kv事件]：")
            .append("--productKey:").append(productKey)
            .append("--mac地址：").append(mac)
            .append("--did:").append(did)
            .append("--airConFunc:").append(airConFunc)
            .append("--sleepDiy:").append(sleepDiy)
            .append("--on_off:").append(onOff)
            .append("--fromReport:")
            .append(fromReport);
    LOG.info(this, logStr.toString());

    // 非制冷或者制热情况下，并且睡眠diy处于开启状态，关闭睡眠diy
    if (null != sleepDiy && sleepDiy == 1) {
      closeSleepDiy(airConFunc, productKey, did);
    }
    //关机状态下清除智能用电设置 add by lixiaoxiao 180508
    if(null != onOff && onOff == 0){
      closeSmartElect(productKey,mac,did);
      return;
    }
    // 非制冷，关闭峰谷节电
    closePeakValley(airConFunc, did);
    // 只处理10分钟上报时间
    if (null != fromReport && fromReport == 1) {
      Integer electricity = data.getInteger("electricity");
      Integer ratedPower = data.getInteger("rated_power");
      // 没有接收到数据，停止处理
      if (null == electricity || null == ratedPower || null == airConFunc) {
        LOG.warn(this, "electricity||ratedPower||airConFunc为空，请留意此事件");
        return;
      }
      String redisKey = CachedConsant.DEVICE_SMART_ELECTRICITY_PREFIX + mac;

      SmartElectricityRedis smartElectricityRedis =
              objectRedis.get(redisKey, SmartElectricityRedis.class);
      if (null == smartElectricityRedis) {
        LOG.info(this, "智能用电:mac:" + mac + "缓存数据为空");
        return;
      }

      if (smartElectricityRedis.isOn()) {
        // 如为非制冷、制热时取消智能用电
        if (!(airConFunc == DatapointConsant.AirConFunConstant.COOL
                || airConFunc == DatapointConsant.AirConFunConstant.HEATING)) {
          closeSmartElect(productKey, mac, did);
          LOG.info(this, "智能用电:mac:" + mac + "处于非制冷或制热,关闭智能用电");
          return;
        }
        StringBuffer smartExcuteTimeStr = new StringBuffer();
        smartExcuteTimeStr
                .append("[智能用电]:")
                .append("--mac：")
                .append(mac)
                .append("--did：")
                .append(did)
                .append("--startHour：")
                .append(smartElectricityRedis.getStartHour())
                .append("--startMinute：")
                .append(smartElectricityRedis.getStartMinute())
                .append("--endHour：")
                .append(smartElectricityRedis.getEndHour())
                .append("--endMinute：")
                .append(smartElectricityRedis.getEndMinute())
                .append("--是否到执行时间：")
                .append(smartElectricityRedis.isExecuteTime())
                .append("--现在时间：")
                .append(
                        NewDateUtils.getCurrentLocalDateTime()
                                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        LOG.info(this, smartExcuteTimeStr.toString());
        if (smartElectricityRedis.isExecuteTime()) {
          int power = smartElectricityExecuteService.executeElectricityPower(
                  mac, electricity, ratedPower);
          smartElecControl(1, productKey, did, power);
          // 智能用电执行一次，执行完一个周期，移除缓存
          if (smartElectricityRedis.getExecuteCycle() == 1
                  && smartElectricityRedis.isExecuteCycleComplete()) {
            closeSmartElect(productKey, mac, did);
          }
        } else {
          smartElecControl(0, productKey, did, defaultPower);
        }
      }
    }
  }

  /**
   * 智能用电控制指令
   *
   * @param smartElectricityStatus
   * @param productKey
   * @param did
   * @param power
   */
  private void smartElecControl(
          int smartElectricityStatus, String productKey, String did, int power) {
    LOG.info(this, "开始执行控制指令==========智能用电-》did:" + did);
    deviceManageService.controlPeakValleyAndSmartElectricity(
            productKey, did, 0, smartElectricityStatus, power);
    LOG.info(this, "执行控制指令结束==========智能用电-》did:" + did);
  }

  /** 非制冷制热模式下 关闭该设备的睡眠DIY */
  private void closeSleepDiy(Integer airConFunc, String productKey, String did) {
    if (airConFunc == null) return;

    if (airConFunc != DatapointConsant.AirConFunConstant.COOL
            && airConFunc != DatapointConsant.AirConFunConstant.HEATING) {
      appControlFuncService.closeAllSleepDiy(productKey, did);
      LOG.info(this, "did:"+did+"[关闭睡眠DIY]");
    }
  }

  /**
   * 关闭智能用电
   *
   * @param productKey
   * @param mac
   * @param did
   */
  private void closeSmartElect(String productKey, String mac, String did) {
    appControlFuncService.closeSmartElectricity(productKey, mac, did);
  }

  /**
   * 非制冷模式下关闭峰谷节电
   *
   * @param airConFunc
   * @param did
   */
  private void closePeakValley(Integer airConFunc, String did) {
    if (airConFunc == null) return;
    AppPeakValleyRedisEntity peakValleyRedisEntity =
            objectRedis.get(
                    CachedConsant.PEAK_VALLEY_REDIS_KEY_PREFIX + did, AppPeakValleyRedisEntity.class);
    if (peakValleyRedisEntity != null && airConFunc != DatapointConsant.AirConFunConstant.COOL) {
      appControlFuncService.closePeakValleyCurve(did);
    }
  }
}
